import 'package:dynamic_stock/comm/loading.dart';
import 'package:dynamic_stock/comm/pie_chart.dart';
import 'package:dynamic_stock/const/const.dart';
import 'package:dynamic_stock/model/home_company_percent.dart';
import 'package:dynamic_stock/model/home_model.dart';
import 'package:dynamic_stock/model/login_model.dart';
import 'package:dynamic_stock/network/network.dart';
import 'package:dynamic_stock/pages/city_page.dart';
import 'package:flutter/material.dart';
import 'package:package_info/package_info.dart';


class HomePage extends StatefulWidget {

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with AutomaticKeepAliveClientMixin {

  DynamicStockList currentModel;
  bool isloading = true;
  List<double> listPercent = [];
  List<Color> listColors = [];
  List<DynamicStockList> companyList;
  LastMonthStatistics _percentModel;

  String version = "1.0";

  @override
  void initState() {
    super.initState();

    _loadData();
  }

  _loadData() async {
    UserData userData = await UserData.instance();

    NetworkTool().request_home({}).then((res){
      if(res.errcode == 0){
        List<double> list = [];
        List<DynamicStockList> companys = [];
        List<Color> colors = [AppMainColor.mainColor];
        int sort = 1;
        res.data.dynamicStockList.forEach((val){
          val.sort = sort;
          sort += 1;
          if(val.saasComId == userData.platComId){
            setState(() {
              currentModel = val;
            });
            list.insert(0, double.parse(val.dynamicStock));
            companys.insert(0, val);
            // 请求公司当月
            _requestCurrentPercent();
          } else {
            list.add(double.parse(val.dynamicStock));
            colors.add(randomColor());
            companys.add(val);
          }
        });
        companyList = companys;
        setState(() {
          listPercent = list;
          listColors = colors;
        });
      } else {
        print(res.message);
      }
    }).whenComplete((){
      setState(() {
        isloading = false;
      });
    });
  }

  _requestCurrentPercent(){
    NetworkTool().request_company_mouth({"saasComId":currentModel.saasComId}).then((res){
      if(res.errcode == 0) {
        setState(() {
          _percentModel = res.data.lastMonthStatistics;
        });
      }
    });
  }

  Widget _createSectionTitle(String title) {
    return Row(
            children: <Widget>[
              Container(
                height: 18,
                width: 2.5, 
                color: AppMainColor.mainColor
              ),
              SizedBox(width: 12,),
              Text(
                title,
                style: TextStyle(color: Color(0xfff35343D),fontSize: 17,fontWeight: FontWeight.w600),
              )
            ],
          );
  }

  Widget _createSectionChild(String title, String desc, double offse) {
    return Padding(
            padding: EdgeInsets.only(top: offse),
            child: Row(
              children: <Widget>[
                Container(
                  width: 160,
                  child: Text(
                    title,
                    style: TextStyle(color: Color(0xff5F5D70)),
                  ),
                ),
                Text(
                  desc,
                  style: TextStyle(color: Color(0xff5F5D70), fontWeight: FontWeight.w500),
                )
              ],
            ),
          );
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    double pieHeight = (MediaQuery.of(context).size.width) * 0.6;

    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text("动态股份", style: AppTextStyle.tabbarTitleStyle),
        elevation: 0.5,
        leading: null,
      ),
      body: LoadingContainer(
        isLoading: isloading,
        child: Container(
            color: Colors.white,
            child: Center(
              child: Column(
                children: <Widget>[
                  Container(
                    padding: const EdgeInsets.fromLTRB(25.5, 27, 25, 0),
                    child: Column(
                      children: <Widget>[
                        _createSectionTitle(_percentModel == null ? "--" : (_percentModel.statisticsTime + "分红")), 
                        _createSectionChild("合伙人当月动态股份(%)",_percentModel == null ? "--" : _percentModel.dynamicStock.toString(), 14),
                        _createSectionChild("合伙人当月股份分红(元)",_percentModel == null ? "--" : _percentModel.lastMonthTotalAmount.toString(), 21),
                        
                        Padding(
                          padding: const EdgeInsets.only(top: 24),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: <Widget>[
                              _createSectionTitle("公司动态股份"),
                              GestureDetector(
                                child: Row(
                                  children: <Widget>[
                                    Text("查看详情",style: TextStyle(color: Color(0xffB2B0C0), fontSize: 12)),
                                    Image.asset("assets/go.png")
                                  ],
                                ),
                                onTap: (){
                                  pushpage(context, CityPage(list: companyList,));
                                },
                              )
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),

                  // 饼图
                  Container(
                    width: pieHeight,
                    height: pieHeight,
                    margin: const EdgeInsets.only(top: 25),
                    child: PieChartWidget(
                      size: pieHeight * 0.5,
                      listColor: listColors,
                      listVal: listPercent,
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.only(top: 20),
                    child: Text(
                      "截止统计时间：${currentModel == null ? '--' : currentModel.statisticsTime}", 
                      style: TextStyle(color: Color(0xffB2B0C0), 
                      fontSize: 12),),
                  ),
                ],
              ),
            ),
          ),
      ),
    );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}